package com.xms.schema.service.optionset;

import com.xms.dependency.XmsDependencyException;
import com.xms.schema.entity.OptionSet;
import com.xms.schema.event.OptionSetDeletedEvent;
import com.xms.utils.CollectionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 删除选项集后，级联删除选项
 * </p>
 *
 * @author migo
 * @since 2021/10/27
 */
@Service
public class OptionSetDetailCascadeDeleter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private IOptionSetDetailDeleterService _optionSetDetailDeleterService;

    @Autowired
    public void OptionSetDetailCascadeDeleter(IOptionSetDetailDeleterService optionSetDetailDeleterService) {
        _optionSetDetailDeleterService = optionSetDetailDeleterService;
    }

    public boolean cascadeDelete(OptionSet... parent) throws SQLException, XmsDependencyException {
        if (CollectionUtil.isEmpty(parent)) {
            return false;
        }
        List<UUID> ids = Arrays.stream(parent).map(x -> x.getOptionsetid()).collect(Collectors.toList());
        for (UUID parentId : ids) {
            _optionSetDetailDeleterService.deleteByOptionsetid(parentId);
        }
        return true;
    }

    @Async
    @EventListener
    public void onApplicationEvent(OptionSetDeletedEvent event) throws XmsDependencyException, SQLException {
        logger.info("OptionSetDetailCascadeDeleting");
        this.cascadeDelete(event.source);
    }
}
